package com.example.thread.d9CompletableFuture2.d7异步任务的交互;

import com.example.thread.d9CompletableFuture2.CommonUtils;

import java.util.Random;
import java.util.concurrent.CompletableFuture;

/**
 * applyToEither()把两个异步任务做比较，异步任务先到结果的，就对先到的结果进行下一步的操作
 */
public class d1_ApplyToEither {
    public static void main(String[] args) {

        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {
            int i = new Random().nextInt(4);
            CommonUtils.sleepSecond(i);
            CommonUtils.printThreadLog("异步任务1休眠了" + i + "秒");
            return "任务1";
        });

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            int i = new Random().nextInt(4);
            CommonUtils.sleepSecond(i);
            CommonUtils.printThreadLog("异步任务2休眠了" + i + "秒");
            return "任务2";
        });

        CompletableFuture<String> future = future1.applyToEither(future2, result -> {
            CommonUtils.printThreadLog("最先到达的结果：" + result);
            return result;
        });

        String join = future.join();
        CommonUtils.printThreadLog("结果是："+join);

        /**
         * CompletableFuture<R> applyToEither(CompletableFuture<T> other,Function<T,R> func)
         * CompletableFuture<R> applyToEitherAsync(CompletableFuture<T> other,Function<T,R> func)
         * CompletableFuture<R> applyToEitherAsync(CompletableFuture<T> other,Function<T,R> func,Executor executor)
         */
    }
}
